<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

use think\exception\ValidateException;
use think\facade\Log;
use util\Excel;

/**
 * Purchaseds控制器
 */
class Purchaseds extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Purchase();

        $this->validate = \app\admin\validate\Purchase::class;
    }

    public function index()
    {
        //是否是超管

        list($limit, $where, $sortArr) = $this->buildTableParames();
        $list = $this->model
            ->field("id,SUM(`num`) as num,admin_id,apply_status,apply_type,merge_batch,merge_time,supply,brand")
            ->where($where)
            ->where(['merge_status' => 1])
            ->order('merge_time desc')
            ->group('merge_batch')
            ->paginate($limit);

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];
        return json($data);
    }

    //审核详情
    public function edit()
    {
        $post = $this->request->post();
        $id = input('id');
        $type = 0;
        if (isset($post['type'])) {
            $type = $post['type'];
        }
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        $merge_batch = !empty($row['merge_batch']) ? $row['merge_batch'] : '';
        if ($type == 1) {
            $list = table('purchase')
                ->field("id,brand,SUM(`num`) as num,admin_id,product_id,apply_type,batch,apply_time,merge_status")
                ->where(['merge_batch' => $merge_batch])
                ->where(['merge_status' => 1])
                ->order('apply_time desc')
                ->group('batch')
                ->select()
                ->toarray();
        } else {
            $list = table('purchase')
                ->field("id,brand,color,num,sku,admin_id,product_id,apply_type,batch,apply_time,merge_status")
                ->where(['merge_batch' => $merge_batch])
                ->where(['merge_status' => 1])
                ->order('apply_time desc')
                ->select()
                ->toarray();
        }
        // halt($list);
        //未审核状态
        foreach ($list as $key => $value) {
            $admin = table('system_admin')->where(['id' => $value['admin_id']])->find();
            $list[$key]['admin_title'] =  !empty($admin['nickname']) ? $admin['nickname'] : '';
            $list[$key]['apply_type_title'] =  $value['apply_type'] == 1 ? '采购申请' : '手动采购';
            $list[$key]['merge_status_title'] = $this->get_merge_status($value['merge_status']);
            if (!empty($value['color']) && !empty($value['color'])) {
                $list[$key]['merge_sku'] = $value['color'] . '-' . $value['sku'];
            } else {
                $list[$key]['merge_sku'] = '';
            }


            $list[$key]['hasChildren'] = true;

            $list_merge_batch = $this->model->where('id', $id)->find();
            if (!empty($list_merge_batch)) {
                $list2['merge_batch'] = $list_merge_batch['merge_batch'];
            } else {
                return error('参数错误请刷新再试');
            }
        }
        $list2['data'] = $list;
        $list2['id'] = $id;
        return success('ok', $list2);
    }

    //通过批次号查询相关信息
    public function  get_info_batch()
    {
        $post = $this->request->post();
        $post['batch'] = !empty($post['batch']) ? $post['batch'] : 0;
        $rst = table('purchase')
            ->field("brand,color,sku,num,apply_time,admin_id,apply_type,merge_status")
            ->where(['batch' => $post['batch']])
            ->group('color,sku')
            ->select()
            ->toarray();
        foreach ($rst as $key => $value) {
            $admin = table('system_admin')->where(['id' => $value['admin_id']])->find();
            $rst[$key]['admin_title'] =  !empty($admin['nickname']) ? $admin['nickname'] : '';
            $rst[$key]['apply_type_title'] =  $value['apply_type'] == 1 ? '采购申请' : '手动采购';
            $rst[$key]['apply_status_title'] = $this->get_merge_status($value['merge_status']);
            $rst[$key]['merge_sku'] = $value['color'] . '-' . $value['sku'];
            $rst[$key]['batch'] = '';
        }
        return success('ok', $rst);
    }

    //获取审核状态

    public  function  get_merge_status($id = '')
    {
        $array = [
            0 => '待合并',
            1 => '待审核',
            2   => '部分待采',
            3  => '待采购',
            4  => '部分待入库',
            5  => '待入库',
            6  => '已完成',
            7 => '审核作废',
            8 => '已驳回',
            9 => '待采购已取消',
        ];
        return isset($array[$id]) ? $array[$id] : '';
    }

    //修改审核状态

    public  function  update_apply_status($id = '', $isarray = false)
    {

        $post = $this->request->post();
        //更新审核状态
        //合并的批次号
        $id = $post['id'];
        $merge_batch  = $post['merge_batch'];
        //查询合并批次号的总条数
        $merge_num = table('purchase')->where(['merge_batch' => $merge_batch, 'merge_status' => 1])->count();
        //已选id
        $select_num = count($id);
        $union_batch  = date('Ymd') . rand(1000, 9999);
        if ($select_num < $merge_num) {
            $merge_status = 2;
        } else {
            $merge_status = 3;
        }
        if (!empty($id) &&  $post['apply_status'] != 2) {
            $merge_status = $post['apply_status'];
            foreach ($id as  $vid) {
                table('purchase')->where(['id' => $vid])->update(['merge_status' => $merge_status, 'union_batch' => $union_batch, 'purchase_time' => date('Y-m-d H:i:s')]);
            }
            return success('更新成功');
        } elseif (!empty($id) && $post['apply_status'] == 2) {
            foreach ($id as  $vid) {
                table('purchase')->where(['id' => $vid])->update(['merge_status' => $merge_status, 'union_batch' => $union_batch, 'purchase_time' => date('Y-m-d H:i:s')]);
            }
            return success('更新成功');
        } else {
            return error('更新失败');
        }
    }

    public  function statistical_sku($id = '')
    {
        $post = $this->request->post();
        $id = $post['id'];
        $ids = is_array($id) ? $id : explode(',', $id);
        $row = table('purchase')
            ->field("id,color,sku,SUM(`num`) as num")
            ->where("id", "in", $ids)
            ->group('color,sku')
            ->limit(100000)
            ->select()
            ->toarray();
        foreach ($row as $key => $value) {
            $row[$key]['merge_sku'] = $value['color'] . '-' . $value['sku'];
        }
        return success('操作成功', $row);
    }
}
